package com.juc.semaphore.semaphore13;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class Service {

    private Semaphore semaphore=new Semaphore(1);
    /**
     * tryAcquire(3, TimeUnit.SECONDS)
     * 在指定时间内尝试的获得1个许可 如果获取不到就返回false
     */

    public void testMethod(){
             try {
                 if(semaphore.tryAcquire(3, TimeUnit.SECONDS)) {
                     System.out.println("threadName = " + Thread.currentThread().getName() + "首选进入！");
                     for (int i = 0; i < Integer.MAX_VALUE; i++) {
                          String newString = new String();
                          Math.random();
                     }
                     semaphore.release();
                 }else {
                     System.out.println("threadName = " + Thread.currentThread().getName() + " 未成功进入！");
                 }
             }catch (InterruptedException e) {
                 e.printStackTrace();
             }
    }
}
